﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//MicroDesigner
using Jc.MicroDesigner.Objects;
using Jc.MicroDesigner.Management;

namespace Jc.MicroDesigner.ToolWindows
{
    /// <summary>
    /// Редактор свойств элементов схемы
    /// </summary>
    public partial class ObjPropertyWindow : Form
    {
        private BaseElement _Element = null;
        private ObjectManager _Manager = null;

        /// <summary>
        /// Создать редактор свойств
        /// </summary>
        public ObjPropertyWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Загрузить свойства элемента
        /// </summary>
        private void LoadProperies()
        {
            if (_Element != null)
            {
                ElementNameBox.Text = _Element.Name;
                ElementDescriptionBox.Text = _Element.Description;
                ElementTypeBox.Text = _Element.GetType().Name;
                Image img = _Element.DrawOptions.DrawToImage();
                ElementPictureBox.Image = img;
                if ((img.Height < ElementPictureBox.Height) && (img.Width < ElementPictureBox.Width))
                    ElementPictureBox.SizeMode = PictureBoxSizeMode.CenterImage;
                else
                    ElementPictureBox.SizeMode = PictureBoxSizeMode.Zoom;

                #region Элементы, имеющие соединения
                if (_Element is CircuitElement)
                {
                    CircuitElement celement = _Element as CircuitElement;
                    foreach (PIN pin in celement.PINs)
                    {
                        PINsTable.Rows.Add();
                        int row = PINsTable.RowCount - 1;
                        PINsTable[0, row].Value = pin.Name;
                        string ptype = pin.TypeToString();
                        PINsTable[1, row].Value = ptype;
                        if (pin.FriendPIN == null)
                            PINsTable[2, row].Value = Properties.Resources.Closed;
                        else
                            PINsTable[2, row].Value = Properties.Resources.Pluged;
                        PINsTable[3, row].Value = pin.DefaultSignal;
                    }
                    // Элементы с задержкой
                    if (_Element is RealElement)
                    {
                        RealElement re = _Element as RealElement;
                        DefaultSignalBox.Text = re.DefaultSignal.ToString();
                        DelayBox.Text = re.Delay.ToString();
                    }
                    else
                        OptionsTab.TabPages.Remove(RealElementPage);
                    //Составные элементы
                    if (_Element is CompositeElement)
                    {
                        SchemePanel.Init((_Element as CompositeElement).InnerScheme);
                    }
                    else
                        OptionsTab.TabPages.Remove(CompositeElementPage);
                }
                else
                {
                    OptionsTab.TabPages.Remove(CircuitTabPage);
                    OptionsTab.TabPages.Remove(RealElementPage);
                    OptionsTab.TabPages.Remove(CompositeElementPage);
                }
                #endregion
            }
        }

        /// <summary>
        /// Сохранить свойства
        /// </summary>
        private void SaveProperies()
        {
            if ((_Element != null) && (_Manager != null))
            {
                if (_Manager.CheckElementName(_Element, ElementNameBox.Text))
                    _Element.Name = ElementNameBox.Text;
                else
                    MessageBox.Show("Новое имя не сохранено.\nЭлемент с таким именем уже есть на схеме.", "Информация",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                _Element.Description = ElementDescriptionBox.Text;
                _Element.DrawOptions.RefreshTemplate();
                if (_Element is CircuitElement)
                {
                    CircuitElement ce = _Element as CircuitElement;
                    for (int i = 0; i < ce.PINs.Count; i++)
                    {
                        sbyte ds = -1;
                        if (SByte.TryParse(PINsTable[3, i].Value.ToString(), out ds))
                            ce.PINs[i].DefaultSignal = ds;
                    }

                    if (_Element is RealElement)
                    {
                        RealElement re = _Element as RealElement;
                        sbyte ds = 0;
                        uint delay = 0;
                        if (SByte.TryParse(DefaultSignalBox.Text, out ds))
                            re.DefaultSignal = ds;
                        if (UInt32.TryParse(DelayBox.Text, out delay))
                            re.Delay = delay;
                    }
                }
            }
        }

        /// <summary>
        /// Показать окно редактора
        /// </summary>
        /// <param name="element">Выбранный элемент</param>
        /// <param name="manager">Схема</param>
        public void ShowDialog(BaseElement element, ObjectManager manager)
        {
            _Element = element;
            _Manager = manager;
            LoadProperies();
            ShowDialog();
        }

        #region Events

        private void OKBtn_Click(object sender, EventArgs e)
        {
            SaveProperies();
            this.Close();
        }

        private void CancelBtn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void PINsTable_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            switch (e.ColumnIndex)
            {
                case 3:
                    sbyte ds = 0;
                    if (!SByte.TryParse(e.FormattedValue.ToString(), out ds))
                    {
                        e.Cancel = true;
                        MessageBox.Show("Неверный начальный сигнал");
                    }
                    break;
            }
        }

        private void DelayBox_Validating(object sender, CancelEventArgs e)
        {
            uint delay = 0;
            if (!UInt32.TryParse(DelayBox.Text, out delay))
            {
                e.Cancel = true;
                MessageBox.Show("Неверная задержка");
            }
        }

        private void DefaultSignalBox_Validating(object sender, CancelEventArgs e)
        {
            sbyte ds = 0;
            if (!SByte.TryParse(DefaultSignalBox.Text, out ds))
            {
                e.Cancel = true;
                MessageBox.Show("Неверный начальный сигнал");
            }
        }

        #endregion
    }
}
